package com.youxin.admin.basic.controller;


import com.youxin.admin.annotation.LoginUser;
import com.youxin.admin.basic.context.FileContext;
import com.youxin.admin.basic.enums.FileTypeEnum;
import com.youxin.admin.basic.model.SysFile;
import com.youxin.admin.basic.service.FileService;
import com.youxin.admin.model.SysUser;
import com.youxin.base.BaseResultCode;
import com.youxin.base.TResult;
import com.youxin.common.config.YouxinCommonProperties;
import com.youxin.exception.SystemException;
import com.youxin.qiniu.QiniuUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("file")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    @Resource
    private FileService fileService;

    @Resource
    private ResourceLoader resourceLoader;

    @Resource
    private YouxinCommonProperties youxinCommonProperties;

    @ApiOperation("上传文件")
    @PostMapping("upload")
    @ResponseBody
    public TResult<String> uploadFile(@LoginUser SysUser sysUser, @RequestParam("file") MultipartFile file, @RequestParam(value = "type", defaultValue = "0") Integer type) {
//        SysFile fileDto = new SysFile();
//        String filePath = youxinCommonProperties.getFilePath();
//        String relFilePath = FileTypeEnum.forType(type).getPath();
//        String fileId = FileContext.primaryId("F");
//        String suffix = FileContext.getFileNameSuffix(file.getOriginalFilename());
//        filePath += relFilePath;
//        try {
//            FileContext.createDir(filePath);
//            FileContext.writeFile(file.getInputStream(), filePath + fileId + suffix);
//        } catch (Exception e) {
//            logger.error("创建文件失败", e);
//            throw new SystemException(BaseResultCode.INTERNAL_ERROR, "文件上传失败");
//        }
//        fileDto.setId(fileId);
//        fileDto.setSuffix(suffix);
//        fileDto.setFilePath(relFilePath);
//        fileDto.setFileSize(file.getSize());
//        fileDto.setFileName(file.getOriginalFilename());
//        fileDto.setCreateBy(sysUser.getUserName());
//        fileDto.setFileType(type);
//        fileService.save(fileDto);
        SysFile sysFile = new SysFile();
        String filePath = youxinCommonProperties.getFilePath();
        String relFilePath = FileTypeEnum.forType(type).getPath();
        String fileId = FileContext.primaryId("F");
        String suffix = FileContext.getFileNameSuffix(file.getOriginalFilename());
        filePath += relFilePath;
        try {
            byte[] bytes = file.getBytes();
            QiniuUtil.upload(bytes, fileId);
        } catch (Exception e) {
            logger.error("创建文件失败", e);
            throw new SystemException(BaseResultCode.INTERNAL_ERROR, "文件上传失败");
        }
        sysFile.setId(fileId);
        sysFile.setSuffix(suffix);
        sysFile.setFilePath(relFilePath);
        sysFile.setFileSize(file.getSize());
        sysFile.setFileName(file.getOriginalFilename());
        sysFile.setCreateBy(sysUser.getUserNo());
        fileService.save(sysFile);
        return TResult.success(youxinCommonProperties.getDownloadUrl() + fileId);
    }

    @ApiOperation("下载文件")
    @GetMapping("download/{id}")
    @ResponseBody
    public void download(@PathVariable String id, HttpServletResponse response) {
        SysFile sysFile = fileService.getById(id);

        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition",
                "attachment;fileName=" + sysFile.getFileName());// 设置文件名
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            String filePath = youxinCommonProperties.getFilePath();
            filePath += sysFile.getFilePath() + sysFile.getId() + sysFile.getSuffix();
            fis = new FileInputStream(filePath);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            logger.error("下载文件出错", e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    logger.error("关闭流出错", e);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    logger.error("关闭流出错", e);
                }
            }

        }
    }
}
